/**
 * Project  : Looker
 * Package  : net.freestu.looker.monitor
 * File     : ImageExtractor.java
 * Author   : solosky < solosky772@qq.com >
 * Date     : Aug 23, 2009
 * Modified : Aug 23, 2009
 * License  : Apache License 2.0 
 */
package net.freestu.looker.monitor;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.freestu.looker.common.Media;
import net.freestu.looker.common.NewsEntity;
import net.freestu.looker.util.URLUtils;


/**
 *  新闻正文图片提取器
 */
public class ImageExtractor extends AbstractExtractor
{

	/**构造函数
     * @param newsEntity
     */
    public ImageExtractor(NewsEntity newsEntity)
    {
	    super(newsEntity);
    }

	/* (non-Javadoc)
     * @see net.freestu.looker.monitor.AbstractExtractor#extract()
     */
    @Override
    public void extract()
    {
		String imgTagRegxp = "<img.*?src=['\"](.*?)['\"].*?>";
		Pattern pt = Pattern.compile(imgTagRegxp,Pattern.CASE_INSENSITIVE);	//不区分大小写
		String content = newsEntity.getContent();
		Matcher mc = pt.matcher(content);
		while (mc.find()){
			String relSrc = mc.group(1);
			String absSrc = URLUtils.real(relSrc, newsEntity.getUrl());
			Media img = new Media();
			img.setUrl(absSrc);
			img.setNewsEntity(newsEntity);
			img.setDate(new Date());
			newsEntity.getMediaList().add(img);	
			
			//替换相对连接为绝对连接
			if(!relSrc.startsWith("http://")){
				content = content.replace(relSrc,absSrc);
			}
			logger.info("成功解析图片:"+img.getUrl());
		}	
		newsEntity.setContent(content);
    }
}